#coding=utf-8
import pymongo
import jieba.posseg as pseg
import sys
reload(sys)
sys.setdefaultencoding("utf8")
class DB(object):

    def connection(self, name):
        """
        数据库连接
        :param name: 数据库名
        :return: 数据库的collection
        """
        connection = pymongo.MongoClient('localhost', 27017)
        db = connection['news']
        collection = db[name]
        return collection

    def read_news(self):
        """
        由新闻id从数据库中获取到新闻内容
        :param news_id: 新闻id号
        :return: 新闻内容
        """
        collection = self.connection('wangyi_news')
        news = list(collection.find().skip(10).limit(10))
        return  news


def pretty_echo_dict(obj, indent=' '):
    def _pretty(obj, indent):
        for i, tup in enumerate(obj.items()):
            k, v = tup
            # 如果是字符串则拼上""
            if isinstance(k, basestring): k = '"%s"' % k
            if isinstance(v, basestring): v = '"%s"' % v
            # 如果是字典则递归
            if isinstance(v, dict):
                v = ''.join(_pretty(v, indent + ' ' * len(str(k) + ': {')))  # 计算下一层的indent
            # case,根据(k,v)对在哪个位置确定拼接什么
            if i == 0:  # 开头,拼左花括号
                if len(obj) == 1:
                    yield '{%s: %s}' % (k, v)
                else:
                    yield '{%s: %s,\n' % (k, v)
            elif i == len(obj) - 1:  # 结尾,拼右花括号
                yield '%s%s: %s}' % (indent, k, v)
            else:  # 中间
                yield '%s%s: %s,\n' % (indent, k, v)

    print ''.join(_pretty(obj, indent))

if __name__ == '__main__':
    db=DB()
    # dic=db.read_news()
    # pretty_echo_dict(dic)
    collection = db.connection('wangyi_news')
    news=collection.find().sort([("news_craw_time",-1)]).skip(5).limit(10)
    if(news!=None):
        news_list=list(news)
    else:
        print ("返回为空")
    for items in news_list:
        print (items["news_craw_time"])